package com.ls.common.annotation;

import com.ls.common.entity.Result;
import com.ls.common.exception.BusinessException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description
 * @Author konglz
 * @Data 2023/4/25 18:43
 */
@Aspect
@Component
@Order(1)
public class IdempotentAspect {

    @Autowired
    StringRedisTemplate redisTemplate;

//    @Pointcut(value = "@within(com.mall.common.annotation.Idempotent)")
//    public void pointcut(){}

    @Before("@annotation(idempotent)")
    public void before(JoinPoint joinPoint, Idempotent idempotent) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) throw new BusinessException(500, "非法请求");

        Boolean flag = redisTemplate.delete("idempotent:" + token);
        if(!flag) throw  new BusinessException(500, "重复的请求");
    }
}
